#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <functional>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogModule;

using fun_t = std::function<std::string(const std::string&, InetAddr&)>;

const int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(uint16_t port, fun_t func)
        : _sockfd(defaultfd),
          _port(port),
          _is_running(false),
          _func(func)
    {
    }

    void init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error!";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd: " << _sockfd;

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error!";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd: " << _sockfd;
    }

    void Start()
    {
        _is_running = true;
        while(_is_running)
        {
            struct sockaddr_in peer;
            memset(&peer, 0, sizeof(peer));
            socklen_t len = sizeof(peer);
            char buffer[1024];

            int s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
            if(s > 0)
            {
                InetAddr client(peer);

                buffer[s] = 0;
                std::string result = _func(buffer, client);
                // std:: cout << "[" << peer_ip << ":" << peer_port << "]# " << buffer << std::endl;

                // std::string echo_string = "server say@ ";
                // echo_string += buffer;
                ssize_t n = sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr*)&peer, sizeof(peer));
                (void)n;
                
            }
        }
    }

    ~UdpServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    bool _is_running;
    fun_t _func;
};